import os
import logging

from dotenv import load_dotenv
from github import Github, Auth
from github import UnknownObjectException
from github import PullRequest, Issue
from data_interface import IssuePRInfo


def get_issue_or_pr_github(repository_name, item_id):
    github_client = Github(auth=Auth.Token(os.getenv("GITHUB_TOKEN")))
    repo = github_client.get_repo(repository_name)
    issue_or_pr = None
    try:
        issue_or_pr = repo.get_pull(item_id)
    except UnknownObjectException:
        logging.log(logging.INFO, f"{item_id} 不是一个PR.")
    else:
        return issue_or_pr
    try:
        issue_or_pr = repo.get_issue(item_id)
    except UnknownObjectException:
        logging.log(logging.INFO, f"{item_id} 不是一个Issue.")
        return None
    return GithubIssuePRInfo(issue_or_pr)


class GithubIssuePRInfo(IssuePRInfo):
    def __init__(self, issue_or_pr):
        if type(issue_or_pr) != PullRequest.PullRequest and type(issue_or_pr) != Issue.Issue:
            raise Exception(f"传入对象类型 {type(issue_or_pr)} 错误.")
        self.title = issue_or_pr.title
        self.labels = [item for item in issue_or_pr.labels]
        self.body = issue_or_pr.body


if __name__ == '__main__':
    load_dotenv()
    logging.basicConfig(level=logging.DEBUG)
    info = get_issue_or_pr_github("llvm/llvm-project", 75048)
    print(info)
